package ru.spbsu.electromenu;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Date: 3/1/11
 * Time: 2:19 PM
 *
 * @author Artem Titov
 */
public class SimpleServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        final String source = "<html>" +
                "<head><title>Welcome to Get/Post servlet</title></head>" +
                "<body>" +
                "Hello. This text is generated by GET method. <br>" +
                "<form action='getpost' method='post'><label>Say the word:</label>&nbsp;<input type='text' name='word'><br>" +
                "<input type='submit' name='say' value='say'></form>" +
                "</body>" +
                "</html>";

        final PrintWriter out = resp.getWriter();
        out.print(source);
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        final String source = "<html>" +
                "<head><title>Welcome to Get/Post servlet</title></head>" +
                "<body>" +
                "Hello. This text is generated by POST method. <br>" +
                ((request.getParameter("say") != null && !isEmpty(request.getParameter("word")))
                        ? "You said: " + request.getParameter("word")
                        : "You said nothing") + "<br>" +
                "<a href='getpost'>Go to the GET page</a> " +
                "</body>" +
                "</html>";

        final PrintWriter out = response.getWriter();
        out.print(source);
        out.close();
    }

    private boolean isEmpty(final String source) {
        return source == null || source.isEmpty();
    }
}
